<template>
  <el-container>
    <el-aside :width="width">
      <div class="left-side">
      <NvForm :nv-data="nvData" @define-event="handleEvent($event)" style="width: 100%">
                      v-if="nvData">
      </NvForm>
      <el-tree
        style="max-width: 400px"
        :data="nvsData.nvs"
        :props="defaultProps"
        show-checkbox
        @node-click="handleNodeClick"
        node-key="id"
        ref="tree"
        default-expand-all
        :check-strictly="true"
      />
      </div>
    </el-aside>
    <el-main>
      <NvLayout :nvs-data="treeDetailData" @define-event="handleEvent($event)">
      </NvLayout>
    </el-main>
  </el-container>
</template>

<script>
import NvForm from './NvForm'
import { ref, onMounted, computed, defineAsyncComponent } from 'vue'
import nvsDataUtils from '../../js/NvsDataUtils'
import layoutService from '../../api/LayoutService'
import cacheManage from '../../cache/CacheManage'
import NvsData from '../../js/NvsData'
import ConstDef from '../../js/ConstDef'
import NvData from '../../js/NvData'
import nvService from '../../api/NvService'
import { ElMessage } from 'element-plus'

export default {
  name: 'TreeLayout',
  components: {
    NvForm,
    NvLayout: defineAsyncComponent(() => import('./NvLayout.vue'))
  },
  props: { nvsData: { type: Object, default: null } },
  setup(props) {
    const layoutExtensions = nvsDataUtils.getLayoutExtension(props.nvsData.layout, ConstDef.LAYOUT_EXTENSION_TYPE_TREE_DETAIL);
    if (layoutExtensions.length !== 1) {
      ElMessage({
        message: "没有配置属性明细扩展页面",
        type: 'error',
        plain: true
      })
      return;
    }
    const extension = JSON.parse(layoutExtensions[0].json);
    const defaultProps = {
      label: extension.labelFdName,
      value: 'id',
      children: props.nvsData.nd.ndName
    };
    const currentNvId = ref(null);
    const detailLayout = ref(null);
    onMounted(async () => {
      if (props.nvsData && props.nvsData.nvs.length > 0) {
        currentNvId.value = props.nvsData.nvs[0].id;
      } else {
        currentNvId.value = 0;
      }
      const commonInfo = cacheManage.getDefaultCommonInfo();
      const layoutMsg = await layoutService.getLayout(commonInfo, extension.layoutCode);
      if (!layoutMsg.success) { return; }
      detailLayout.value = layoutMsg.value;
    });
    const treeDetailData = computed(() => {
      const nd = props.nvsData.nd;
      const nv = nvsDataUtils.searchNvById(currentNvId.value, props.nvsData.nvs, nd);
      return new NvsData([nv], nd, detailLayout.value)
    });
    const nvData = computed(() => {
      return new NvData(props.nvsData.nvs, props.nvsData.nvs[0], props.nvsData.nd, props.nvsData.layout)
    });

    const width = ref("20%");
    return {
      defaultProps,
      treeDetailData,
      nvData,
      currentNvId,
      width
    }
  },
  methods: {
    async handleEvent (event) {
      const fvData = event.fvData;
      const functionCode = fvData.fdLayout.functionCode;
      if (functionCode === ConstDef.FUNCTION_CODE_ADD_NODE) {
        this.addTreeNode(event);
      } else if (functionCode === ConstDef.FUNCTION_CODE_DELETE_NODE) {
        this.deleteTreeNode(event);
      } else {
        this.$emit("define-event", event);
      }
    },
    async addTreeNode(event) {
      const selected = this.$refs.tree.getCheckedNodes();
      if (selected.length === 0) {
        ElMessage({
          message: '请选择节点.',
          type: 'error',
          plain: true
        })
      } else if (selected.length > 1) {
        ElMessage({
          message: '不能多选.',
          type: 'error',
          plain: true
        })
      } else {
        const commonInfo = cacheManage.getDefaultCommonInfo();
        const nvMsg = await nvService.initNv(commonInfo, this.nvsData.nd.ndCode);
        if (!nvMsg.success) { return; }
        const ndName = this.nvsData.nd.ndName;
        selected[0][ndName].push(nvMsg.value);
        this.currentNvId = nvMsg.value.id;
        setTimeout(() => {
          this.$refs.tree.setCheckedKeys([this.currentNvId]);
        })
      }
    },
    async deleteTreeNode(event) {
      const selected = this.$refs.tree.getCheckedNodes();
      if (selected.length === 0) {
        ElMessage({
          message: '请选择节点.',
          type: 'error',
          plain: true
        })
        return;
      }
      for (const item of selected) {
        if (item.id > 0) {
          const commonInfo = cacheManage.getDefaultCommonInfo();
          const msg = await nvService.deleteNvById(commonInfo, this.nvsData.nd.ndName, item.id);
          if (msg.success) {
            nvsDataUtils.searchAndDeleteNvById(item.id, this.nvsData.nvs, this.nvsData.nd);
          } else {
            return;
          }
        } else {
          nvsDataUtils.searchAndDeleteNvById(item.id, this.nvsData.nvs, this.nvsData.nd);
        }
      }
    },

    handleNodeClick(data, node, self, parent) {
      this.currentNvId = data.id;
      this.$refs.tree.setCheckedKeys([data.id]);
    }
  }
}
</script>

<style lang="scss" scoped>
  .left-side{
    padding-top: 20px;

  }
</style>
